<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>可以模糊搜索的下拉菜单</title>
<script src="../js/commonJs.js"></script>
<script type="text/javascript" src="//res.waygc.net/jQuery/jquery-3.4.1.min.js"></script>
</head>
<body>
<p><div class="like_search_box">
	<input class="needs_input" onkeyup="changeNeedsInput(this)"  id="needs_input" />
	<input id="needs_hidden" type="hidden" name="needs_name" />
	<select class="like_search_select" id="select_needs_list" size="10" style="display:none;"></select>
</div></p>
<p>可用数据：</p>
<ul>
    <li>牙膏厂</li>
    <li>熊厂</li>
    <li>企鹅公司</li>
    <li>粗粮公司</li>
    <li>菊花社</li>
    <li>美帝良心想</li>
    <li>养猪场</li>
</ul>
<script type="text/javascript">
// 这部分用AJAX或者其他方式获得
var proto = [
    {
        name: "牙膏厂",
        corpId: '1234'
    }, {
        name: "熊厂",
        corpId: '1235'
    }, {
        name: "企鹅公司",
        corpId: '1236'
    }, {
        name: "粗粮公司",
        corpId: '1237'
    }, {
        name: "菊花社",
        corpId: '1238'
    }, {
        name: "美帝良心想",
        corpId: '1239'
    }, {
        name: "养猪场",
        corpId: '1240'
    }
];

function changeNeedsInput(element) {

    // 这部分是AJAX替换
    var list = [];
    var str = element.value;

    for (var i = 0, len = proto.length; i < len; i++) {
        var item = proto[i];
        if (item.name.indexOf(str) >= 0) {
            list.push(item);
        }
	}

    // list的具体实现交给后台sql决定
    var select = $("#select_needs_list");

    if (!str) {// 空输入时隐藏select
        select.empty();
        select.css({
            "display": "none"
        });
        return;
    };

    var input = $("#needs_input");
    var hiddenInput = $("#needs_hidden");

    setTimeout(function () { // TODO AJAX 替换位

        select.empty();

        for (var i = 0, len = list.length; i < len; i++) {
            (function(item) {
                var option = $("<option value='" + item.corpId + "'>" + item.name + "</option>");
                option.css({
                    "height": 22 * list + "px",
                    "padding":"2px"
                });
                option.on('click', function () {
                    input.val(item.name);
                    hiddenInput.val(item.corpId);
                    select.css({
                        "display": "none"
                    });
                });
                select.append(option);
            })(list[i]);

        }

        if (list.length > 0) {
            select.css({
                "display": "block",
                "height": 24 * list.length + "px"
            });
        }

    }, 100);// 从后台加载数据
}
</script>
</body>
</html>